package com.fauks.ssm.mybatis;

import com.fauks.ssm.mybatis.bean.CacheBean;
import com.fauks.ssm.mybatis.mapper.ICacheMapper_temp;
import com.fauks.ssm.mybatis.utils.MyBatisUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * 测试Mybatis缓存
 */
public class _06TestCacheAndAnnotation {

    private ICacheMapper_temp cacheMapper;

    /**
     * 测试二级缓存
     */
    @Test
    public void testSecondCahce() throws IOException {
        //此处要注意必须为同一SqlSessionFactory
        InputStream is = Resources.getResourceAsStream("mybatis/SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        cacheMapper = sqlSession.getMapper(ICacheMapper_temp.class);
        CacheBean cacheBean1 = cacheMapper.selectById(1);
        System.out.println(cacheBean1);

        //关闭session一级缓存被清空，但是二级缓存还在
        sqlSession.close();

        sqlSession = sqlSessionFactory.openSession();
        cacheMapper = sqlSession.getMapper(ICacheMapper_temp.class);
        CacheBean cacheBean2 = cacheMapper.selectById(1);
        System.out.println(cacheBean2);
        sqlSession.close();
    }

    @Test
    public void testDeleteByAnnotation(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        cacheMapper = sqlSession.getMapper(ICacheMapper_temp.class);
        cacheMapper.deleteCacheBean(1);
        sqlSession.close();
    }

}
